﻿using System;
using System.Collections.Generic;
using System.Text;

public enum PurchaseVerifyResult
{
    // 请求粗偶
    HttpRequestError,
    // 假的凭据
    FakeReceipt,
    // 成功
    Success,
}
public class UDPReceiptVerify
{
    const int maxTryCount = 5;

    int m_TryCount;

    //string m_ProductId;
    //string m_PackageName;
    string m_QueryToken;
    string m_ClientId;
    string m_OrderId;
    string m_ClientSerect;

    private PurchaseVerifyResult m_ResultStatus;
    public PurchaseVerifyResult resultStatus => m_ResultStatus;

    Action<UDPReceiptVerify> m_OnResult;

    public UDPReceiptVerify(
        bool allowTest,
        //string internalOder, 
        string purchasesToken,
        string packageName,
        string productId,
        string clientId,
        string clientSerect,
        Action<UDPReceiptVerify> callBack // 回调
    )
    {
        //m_AllowTest = allowTest;
        //// m_InternalOder = internalOder;
        //m_PurchasesToken = purchasesToken;
        //m_PackageName = packageName;
        //m_ProductId = productId;

        m_OnResult = callBack;
        try
        {
            if(string.IsNullOrEmpty(purchasesToken))
            {
                OnOrderValidateFailed("receipt empty");
                return;
            }
            Dictionary<string, object> json = MiniJSON.Json.Deserialize(purchasesToken) as Dictionary<string, object>;
            if (json == null)
            {
                OnOrderValidateFailed("parse receipt error");
                return;
            }
            bool success =
                json.ContainsKey("OrderQueryToken")
                 && json.ContainsKey("GameOrderId")
                 && json.ContainsKey("ProductId")
                ;
            if (!success)
            {
                OnOrderValidateFailed("invalid receipt");
                return;
            }
            string queryToken = (string)json["OrderQueryToken"];
            string orderId = (string)json["GameOrderId"];

            Init(queryToken, clientId, orderId, clientSerect);
        }
        catch(Exception e)
        {
            GameDebug.LogError(e.Message + "\n" + e.StackTrace);
        }
    }

    public void Init( string queryToken, string clientId, string orderId, string clientSerect)
    {
        m_QueryToken = queryToken;
        m_ClientId = clientId;
        m_OrderId = orderId;
        m_ClientSerect = clientSerect;

    }

    public void Verify()
    {
        OrderQuery(m_QueryToken, m_ClientId, m_OrderId, m_ClientSerect);
    }

    void OrderQuery(string queryToken,string clientId,string orderId,string clientSerect)
    {
        string str = queryToken + clientSerect;

        string sign = MD5Helper.MD5(str);

        string url = "https://distribute.dashboard.unity.com/udp/developer/api/order";

        url += $"?orderQueryToken={queryToken}&clientId={clientId}&orderId={orderId}&sign={sign}";

        GameDebug.Log(($"request url:{url}"));

        AsyncHttpRequest request = new AsyncHttpRequest(url);
        request.Timeout = 20000;
        request.onResponse = (req) =>
        {
            if (string.IsNullOrEmpty(req.error))
            {
                OnOrderQuesyRes(req.response);
            }
            else
            {
                GameDebug.Log($"error: {req.error}");
                this.OnHttpErr(req.error);
            }
        };

        request.GET();
    }

    private void OnOrderQuesyRes(string response)
    {
        GameDebug.Log($"OnOrderQueryRes:\n{response} ");
        try
        {
            Dictionary<string, object> json = MiniJSON.Json.Deserialize(response) as Dictionary<string, object>;
            if (json == null)
            {
                //this.OnVerifyFail();
                return;
            }
            bool success =
                json.ContainsKey("ClientId")
                 && json.ContainsKey("CpOrderId")
                 && json.ContainsKey("ProductId")
                 /* && json.ContainsKey("ChannelType")
                  && json.ContainsKey("Currency") 
                  && json.ContainsKey("Amount")
                  &&  json.ContainsKey("Country")
                  && json.ContainsKey("Quantity")
                  && json.ContainsKey("Rev") &&*/
                 && json.ContainsKey("Status")
                /*&& json.ContainsKey("PaidTime")
                 && json.ContainsKey("Extension")*/
                ;
            if (!success)
            {
                this.OnOrderValidateFailed("parse response failed.");
                return;
            }

            string status = (string)json["Status"];

            if (status.Equals("SUCCESS"))
            {
                GameDebug.Log("验证订单成功");
                OnValidateSuc();
            }
            else
            {
                GameDebug.LogError("验证订单失败");
                OnOrderValidateFailed("Verify order failed.");
            }


        }
        catch (Exception e)
        {
            GameDebug.Log($"{e}");
        }
    }


    void OnHttpErr(string err)
    {
        GameDebug.LogError($"Http reqeust error:{err}");

        m_ResultStatus = PurchaseVerifyResult.HttpRequestError;
        this.m_OnResult?.Invoke(this);
    }

    void OnOrderValidateFailed(string err)
    {
        GameDebug.LogError($"OnOrderValidateFailed error:{err}");

        m_ResultStatus = PurchaseVerifyResult.FakeReceipt;
        this.m_OnResult?.Invoke(this);
    }

    void OnValidateSuc()
    {
        m_ResultStatus = PurchaseVerifyResult.Success;
        this.m_OnResult?.Invoke(this);
    }


    public void TestQueryingOrders()
    {
        /*string channelProductId = "com.zhan.petsfight.diamond1";
        string channelType = "UDP";
        string clientId = "AAIgx9VcFh2YCVqmK6UcCQ";
        string cpOrderId = "2a4d91f8483f47b9ac1a4f9000d5a54a";
        string packageName = "com.zhan.petsifght";*/

        string queryToken = "eyJjaGFubmVsUHJvZHVjdElkIjoiY29tLnpoYW4ucGV0c2ZpZ2h0LmRpYW1vbmQxIiwiY2hhbm5lbFR5cGUiOiJVRFAiLCJjbGllbnRJZCI6IjRzSDBvYzcxUzViYkg5Z1NxRzBWVmciLCJjcE9yZGVySWQiOiI4YWU0NDgwM2I5MzY0ZGZmYWZkNTI4ZTlhMGU2NWI2ZCIsInBhY2thZ2VOYW1lIjoiY29tLnpoYW4ucGV0c2ZpZ2h0In0=";

        GameDebug.Log($"orderQueryToken:\n{Encoding.UTF8.GetString(Convert.FromBase64String(queryToken))}");

        string clientId = "4sH0oc71S5bbH9gSqG0VVg";
        string orderId = "8ae44803b9364dffafd528e9a0e65b6d";

        string clientSerect = "ChiWqzxhQ8LkukD1IPGQ-dDvAtyayQ3Z5HnWnZfwPs4";
        string str = queryToken + clientSerect;

        string sign = MD5Helper.MD5(str);

        string url = "https://distribute.dashboard.unity.com/udp/developer/api/order";

        url += $"?orderQueryToken={queryToken}&clientId={clientId}&orderId={orderId}&sign={sign}";

        GameDebug.Log(($"request url:{url}"));

        AsyncHttpRequest request = new AsyncHttpRequest(url);
        request.Timeout = 20000;
        request.onResponse = (req) =>
        {
            if (string.IsNullOrEmpty(req.error))
            {
                OnOrderQuesyRes(req.response);
            }
            else
            {
                GameDebug.Log($"error: {req.error}");
            }
        };

        request.GET();
    }
}

